<template>
    <div class="chat-panel">
        <div class="chat-header">
            <div class="user-info">
                <el-avatar :size="40" :src="friend.userPicture" class="user-avatar" @click="showUserProfile(friend.userEmail)"></el-avatar>
                <div class="user-details">
                    <div class="user-name" @click="showUserProfile(friend.userEmail)">
                        {{ friend.userName }}
                        <span class="user-rank" :class="getRankClass(friend.userRank)">
                            {{ getRankLabel(friend.userRank) }}
                        </span>
                    </div>
                    <div class="user-status">
                        <span class="status-dot online"></span>
                        <span class="status-text">在线</span>
                    </div>
                </div>
            </div>
            <div class="chat-actions">
                <el-tooltip content="搜索聊天记录" placement="bottom">
                    <button class="action-btn"><i class="el-icon-search"></i></button>
                </el-tooltip>
                <el-tooltip content="语音通话" placement="bottom">
                    <button class="action-btn"><i class="el-icon-phone"></i></button>
                </el-tooltip>
                <el-tooltip content="视频通话" placement="bottom">
                    <button class="action-btn"><i class="el-icon-video-camera"></i></button>
                </el-tooltip>
            </div>
        </div>

        <div class="chat-body">
            <div class="messages" ref="messageList">
                <div v-if="messages.length === 0" class="empty-chat">
                    <i class="el-icon-chat-dot-round"></i>
                    <p>与{{ friend.userName }}的聊天开始了</p>
                </div>

                <template v-for="(message, index) in messages">
                    <!-- 日期分隔线 -->
                    <div v-if="showDateDivider(message, index)" :key="`date-${index}`" class="date-divider">
                        <span>{{ formatMessageDate(message) }}</span>
                    </div>

                    <!-- 消息气泡 -->
                    <div :key="index" class="message-row" :class="{
                        'outgoing': message.to === friend.userEmail,
                        'incoming': message.from === friend.userEmail
                    }">
                        <div class="avatar-container" v-if="message.from === friend.userEmail">
                            <el-avatar :size="36" :src="friend.userPicture"></el-avatar>
                        </div>
                        <div class="message">
                            <div class="message-time">{{ formatMessageTime(message) }}</div>
                            <div class="message-content">
                                <p>{{ message.content }}</p>
                            </div>
                            <div class="message-status" v-if="message.to === friend.userEmail">
                                <i class="el-icon-check"></i>
                            </div>
                        </div>
                        <div class="avatar-container" v-if="message.to === friend.userEmail">
                            <el-avatar :size="36" :src="store.state.me.userPicture"></el-avatar>
                        </div>
                    </div>
                </template>
            </div>

            <div class="typing-indicator" v-if="isTyping">
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <span>对方正在输入...</span>
            </div>

            <div class="message-composer">
                <div class="composer-input">
                    <el-input
                        v-model="newMessage"
                        type="textarea"
                        :rows="3"
                        resize="none"
                        placeholder="输入消息..."
                        @keyup.enter.native="sendMessage"
                    ></el-input>
                </div>

                <div class="composer-actions">
                    <el-button
                        type="primary"
                        :disabled="!newMessage.trim()"
                        @click="sendMessage"
                        class="send-btn"
                    >
                        <i class="el-icon-position"></i>
                        <span>发送</span>
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 用户信息弹窗 -->
        <el-dialog
          title="用户信息"
          :visible.sync="userProfileVisible"
          width="500px"
          custom-class="user-profile-dialog"
          :before-close="handleCloseUserProfile">
          <div v-if="selectedUser" class="user-profile-content">
            <div class="user-profile-header">
              <el-avatar :size="80" :src="selectedUser.userPicture || defaultAvatar"></el-avatar>
              <div class="user-profile-info">
                <h3>{{ selectedUser.userName }}</h3>
                <p>{{ selectedUser.userEmail }}</p>
              </div>
            </div>
            <div class="user-profile-details">
              <div class="detail-item">
                <span class="detail-label">专业：</span>
                <span class="detail-value">{{ getDeptName(selectedUser.dept_id) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">性别：</span>
                <span class="detail-value">{{  selectedUser.userSex || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">年龄：</span>
                <span class="detail-value">{{ selectedUser.userAge || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">国籍：</span>
                <span class="detail-value">{{ selectedUser.userFrom || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">个人简介：</span>
                <p class="detail-value">{{ selectedUser.userSelf || '暂无简介' }}</p>
              </div>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="userProfileVisible = false">关闭</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
import {addMessage, getMessageList, getUserInfo} from "@/api/api";
import store from "@/store";
import { getRankClass, getRankLabel } from "@/utils/rankUtils";

export default {
    name: "Chat",
    computed: {
        store() {
            return store
        }
    },
    data() {
        return {
            friend: null,
            active: null,
            newMessage: '',
            messages: [],
            loading: false,
            isTyping: false,
            typingTimeout: null,
            lastMessageDate: null,
            userProfileVisible: false,
            selectedUser: null,
            defaultAvatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
        };
    },
    methods: {
        getRankClass,
        getRankLabel,
        async sendMessage() {
            if (this.newMessage.trim() !== '') {
                this.loading = true;

                const messageObj = {
                    to: this.friend.userEmail,
                    from: this.store.state.me.userEmail,
                    content: this.newMessage,
                    timestamp: new Date().toISOString()
                };

                this.messages.push(messageObj);

                const message = this.newMessage;
                this.newMessage = '';

                this.store.state.websocket.send(JSON.stringify({
                    type: 'message',
                    message: message,
                    to: this.friend.userEmail,
                    from: this.store.state.me.userEmail,
                }));

                const response = await addMessage({
                    to: this.friend.userEmail,
                    content: message,
                });
                if (response.data.message === "成功") {
                    this.scrollToBottom();
                } else {
                    this.$message.error("发送信息失败");
                    this.messages.pop();
                }
                this.loading = false;
            }
        },
        async InitMessages(userEmail) {
            try {
                this.loading = true;
                const response = await getMessageList({
                    params: {
                        to: userEmail,
                    },
                });
                if (response && response.data && response.data.data) {
                    this.messages = response.data.data.map(msg => ({
                        ...msg,
                        timestamp: msg.timestamp || new Date().toISOString()
                    }));
                    this.scrollToBottom();
                }
                this.loading = false;
            } catch (error) {
                console.error('Error fetching messages:', error);
                this.loading = false;
            }
        },
        scrollToBottom() {
            this.$nextTick(() => {
                const messageList = this.$refs.messageList;
                if (messageList) {
                    messageList.scrollTop = messageList.scrollHeight;
                }
            });
        },
        formatMessageTime(message) {
            if (!message.time) return '';

            const date = new Date(message.time);
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');

            return `${hours}:${minutes}`;
        },
        formatMessageDate(message) {
            if (!message.time) return '';

            const date = new Date(message.time);
            const today = new Date();
            const yesterday = new Date();
            yesterday.setDate(yesterday.getDate() - 1);

            const isToday = date.toDateString() === today.toDateString();
            const isYesterday = date.toDateString() === yesterday.toDateString();

            if (isToday) {
                return '今天';
            } else if (isYesterday) {
                return '昨天';
            } else {
                const year = date.getFullYear();
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const day = date.getDate().toString().padStart(2, '0');
                return `${year}-${month}-${day}`;
            }
        },
        showDateDivider(message, index) {
            if (index === 0) return true;

            const currentDate = new Date(message.time || new Date());
            const prevDate = new Date(this.messages[index - 1].time || new Date());

            return currentDate.toDateString() !== prevDate.toDateString();
        },
        simulateTyping() {
            this.isTyping = true;
            if (this.typingTimeout) clearTimeout(this.typingTimeout);

            this.typingTimeout = setTimeout(() => {
                this.isTyping = false;
            }, 3000);
        },
        // 获取部门名称
        getDeptName(deptId) {
            if (!deptId) return '未设置';
            const dept = this.$store.state.deptList.find(dept => dept.dept_id === deptId);
            return dept ? dept.dept_name : '未知部门';
        },

        // 显示用户个人主页
        async showUserProfile(userEmail) {
            if (!userEmail) return;

            this.loading = true;
            try {
                const response = await getUserInfo(userEmail);
                if (response.data.message === "成功") {
                    this.selectedUser = response.data.data;
                    this.userProfileVisible = true;
                } else {
                    this.$message.error("获取用户信息失败");
                }
            } catch (error) {
                console.error("获取用户信息出错:", error);
                this.$message.error("获取用户信息出错");
            } finally {
                this.loading = false;
            }
        },

        // 关闭用户个人主页
        handleCloseUserProfile() {
            this.userProfileVisible = false;
            this.selectedUser = null;
        },
    },
    mounted() {
        this.friend = this.$route.query.count;

        // 保存原始监听器
        const originalOnMessage = this.$store.state.websocket.onmessage;

        // 设置当前页面的监听逻辑
        this.$store.state.websocket.onmessage = (event) => {
            // 先执行原有逻辑（如全局未读计数）
            if (originalOnMessage) originalOnMessage(event);

            // 再执行当前页面的专属逻辑
            const message = JSON.parse(event.data);
            if (message.type === 'message' && this.friend && message.from === this.friend.userEmail) {
                this.messages.push({
                    to: message.to,
                    from: message.from,
                    content: message.content,
                    timestamp: new Date().toISOString()
                });
            }
        };

        // 保存当前监听器引用，用于销毁时恢复
        this.currentOnMessage = this.$store.state.websocket.onmessage;
    },
    beforeDestroy() {
        // 恢复为原始监听器（移除非全局逻辑）
        if (this.currentOnMessage) {
            this.$store.state.websocket.onmessage = this.currentOnMessage;
        }
    },
    watch: {
        '$route.query.count': {
            immediate: true,
            handler(newCount) {
                this.friend = newCount;
                if (this.friend && this.friend.userEmail) {
                    this.InitMessages(this.friend.userEmail);
                    // 标记该用户的消息为已读
                    this.store.commit('markAsRead', this.friend.userEmail);
                }
            }
        },
        messages: {
            deep: true,
            handler() {
                this.scrollToBottom();
            }
        },
        newMessage(val) {
            if (val && this.friend) {
                this.store.state.websocket.send(JSON.stringify({
                    type: 'typing',
                    to: this.friend.userEmail,
                    from: this.store.state.me.userEmail
                }));
            }
        }
    }
}
</script>

<style scoped>
.chat-panel {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: white;
    border-radius: 8px;
    overflow: hidden;
}

.chat-header {
    padding: 12px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #dadce0;
    background-color: white;
}

.user-info {
    display: flex;
    align-items: center;
}

.user-avatar {
    border: 2px solid #e8f0fe;
}

.user-details {
    margin-left: 12px;
}

.user-name {
    font-weight: 500;
    color: #202124;
    font-size: 16px;
}

/* 用户等级样式已移至全局样式中 */

.user-status {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: #5f6368;
    margin-top: 2px;
}

.status-dot {
    height: 8px;
    width: 8px;
    border-radius: 50%;
    margin-right: 5px;
}

.status-dot.online {
    background-color: #34a853;
}

.chat-actions {
    display: flex;
    gap: 8px;
}

.action-btn {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    border: none;
    background-color: transparent;
    color: #5f6368;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: background-color 0.2s;
}

.action-btn:hover {
    background-color: #f1f3f4;
}

.action-btn i {
    font-size: 18px;
}

.chat-body {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #f8f9fa;
    position: relative;
    overflow: hidden;
    padding-bottom: 30px;
}

.messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    scroll-behavior: smooth;
}

.empty-chat {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #5f6368;
}

.empty-chat i {
    font-size: 48px;
    margin-bottom: 16px;
    color: #dadce0;
}

.date-divider {
    text-align: center;
    margin: 16px 0;
}

.date-divider span {
    padding: 4px 12px;
    background-color: #e8f0fe;
    border-radius: 16px;
    font-size: 12px;
    color: #1a73e8;
}

.message-row {
    display: flex;
    margin-bottom: 16px;
    align-items: flex-end;
}

.incoming {
    justify-content: flex-start;
}

.outgoing {
    justify-content: flex-end;
}

.avatar-container {
    margin: 0 8px;
}

.message {
    display: flex;
    flex-direction: column;
    max-width: 65%;
}

.incoming .message {
    align-items: flex-start;
}

.outgoing .message {
    align-items: flex-end;
}

.message-time {
    font-size: 11px;
    color: #5f6368;
    margin-bottom: 4px;
}

.message-content {
    padding: 12px 16px;
    border-radius: 18px;
    position: relative;
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.15);
}

.incoming .message-content {
    background-color: white;
    border-top-left-radius: 4px;
    color: #202124;
}

.outgoing .message-content {
    background-color: #1a73e8;
    border-top-right-radius: 4px;
    color: white;
}

.message-content p {
    margin: 0;
    line-height: 1.4;
    font-size: 15px;
    white-space: pre-wrap;
    word-break: break-word;
}

.message-status {
    font-size: 12px;
    color: #34a853;
    margin-top: 4px;
}

.typing-indicator {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 18px;
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.15);
    position: absolute;
    bottom: 190px;
    left: 20px;
    font-size: 13px;
    color: #5f6368;
}

.typing-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #1a73e8;
    margin-right: 4px;
    animation: typing 1.5s infinite;
    opacity: 0.7;
}

.typing-dot:nth-child(1) { animation-delay: 0s; }
.typing-dot:nth-child(2) { animation-delay: 0.3s; }
.typing-dot:nth-child(3) { animation-delay: 0.6s; }

@keyframes typing {
    0% { transform: translateY(0); }
    50% { transform: translateY(-5px); }
    100% { transform: translateY(0); }
}

.message-composer {
    padding: 16px;
    padding-bottom: 30px;
    background-color: white;
    border-top: 1px solid #dadce0;
    position: relative;
    bottom: 16px;
    margin-bottom: -16px;
}

.composer-input {
    margin-bottom: 12px;
    margin-top: 16px;
}

.composer-input >>> .el-textarea__inner {
    border-radius: 8px;
    border: 1px solid #dadce0;
    padding: 12px;
    font-size: 15px;
    transition: all 0.2s;
}

.composer-input >>> .el-textarea__inner:focus {
    border-color: #1a73e8;
    box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
}

.composer-actions {
    display: flex;
    justify-content: flex-end;
}

.send-btn {
    border-radius: 24px;
    background-color: #1a73e8;
    border: none;
    padding: 8px 16px;
    font-weight: 500;
    transition: all 0.2s;
}

.send-btn:hover:not(:disabled) {
    background-color: #1765c9;
    transform: translateY(-1px);
}

.send-btn:disabled {
    background-color: #dadce0;
    color: #9aa0a6;
}

.send-btn i {
    margin-right: 6px;
}

.user-profile-dialog {
    /* Add your styles for the user profile dialog here */
}

.user-profile-content {
    /* Add your styles for the user profile content here */
}

.user-profile-header {
    /* Add your styles for the user profile header here */
}

.user-profile-info {
    /* Add your styles for the user profile info here */
}

.user-profile-details {
    /* Add your styles for the user profile details here */
}

.detail-item {
    /* Add your styles for the detail item here */
}

.detail-label {
    /* Add your styles for the detail label here */
}

.detail-value {
    /* Add your styles for the detail value here */
}
</style>
